package io.gitee.kotle.android

import com.android.tools.idea.wizard.template.RecipeExecutor
import com.android.tools.idea.wizard.template.activityToLayout
import java.io.File

/**
 * 推荐生成的布局文件名字
 */
fun createLayoutName(className: String): String {
    val array = className.toCharArray()
    val string = StringBuilder()
    array.forEach {
        if (it.isUpperCase()) {
            string.append("_")
            string.append(it.toLowerCase())
        } else {
            string.append(it)
        }
    }
    return string.toString()
}

/**
 * 通过布局文件名获取bindingName
 */
fun getBindingName(layoutName: String): String {
    val sb = StringBuilder()
    var nextNeedUp = true
    layoutName.forEach {
        nextNeedUp = if (it == '_') {
            true
        } else {
            if (nextNeedUp) {
                sb.append(it.toUpperCase())
            } else {
                sb.append(it)
            }
            false
        }
    }
    return sb.toString()+"Binding"
}


/**
 * 保存布局文件
 */
fun RecipeExecutor.saveLayout(
        classPath: String,
        fullClassName: String,
        resOut: File, layoutName: String
) {
    save(
            getLayoutStr(classPath, fullClassName),
            resOut.resolve("layout/${layoutName}.xml")
    )
}

private fun getLayoutStr(classPath: String, fullClassName: String) = """
    <?xml version="1.0" encoding="utf-8"?>
    <widget.CompatConstraint xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="${classPath}.${fullClassName}">

    </widget.CompatConstraint>
"""